package com.isorf.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.isorf.mapper.InventoryMapper;
import com.isorf.mapper.ShoeImageMapper;
import com.isorf.mapper.ShoeMapper;
import com.isorf.pojo.Shoe;
import com.isorf.pojo.ShoeImage;
import com.isorf.service.ShoeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ShoeServiceImpl implements ShoeService {
    @Autowired
    private ShoeMapper shoeMapper;
    @Autowired
    private InventoryMapper inventoryMapper;
    @Autowired
    private ShoeImageMapper shoeImagesMapper;


    /**
     * 添加鞋子
     * 在添加鞋子的同时，需要向库中添加库存信息
     * 在添加鞋子的同时，需要图片表中添加图片信息
     * @param shoe
     * @return
     */
    @Override
    @Transactional     //原子性，事务注解，方法内多个数据库操作，只要有一个失败，则回滚
    public Boolean addShoe(Shoe shoe) {
        //调用ShoeMpper添加鞋子
        int result = shoeMapper.addShoe(shoe);    //向鞋子里添加数据时，把自动增长的shoeId拿过来
        int flag = 0;
        if(result>0){    //鞋子信息添加成功
            //调用库存的方法添加库存信息
            flag = inventoryMapper.addInventoryList(shoe.getShoeId(), shoe.getInventoryList());
        }
        int flag2 = 0;
        if(flag>0){    //库存信息添加成功
            //调用图片的方法添加图片信息
            int shoeId = shoe.getShoeId();
            List<ShoeImage> shoeImages = shoe.getShoeImages();
            flag2 = shoeImagesMapper.insertShootImages(shoeId,shoeImages);
        }

       return flag2>0;
    }

    @Override
    public Boolean deleteShoe(int shoeId) {
        int result = shoeMapper.deleteShoe(shoeId);
        return result > 0;
    }

    @Override
    @Transactional
    public Boolean updateShoe(Shoe shoe) {
        //调用鞋子的Mapper方法修改改鞋子信息的同时，修改库存信息
        int result = shoeMapper.updateShoe(shoe);
        int flag = inventoryMapper.updateInventoryList(shoe.getInventoryList());
        //同时处理图片的信息
        //根据shoeId 把之前和shoeId 相同的图片删除  批量删除
        int d = shoeImagesMapper.deleteShoeImages(shoe.getShoeImages());
        //添加新的图片信息   批量插入图片
        int i = shoeImagesMapper.insertShootImages(shoe.getShoeId(), shoe.getShoeImages());


        return result > 0 || flag > 0 || d > 0 || i > 0;
    }

    @Override
    public Shoe getShoeById(int shoeId) {
        return shoeMapper.getShoeById(shoeId);
    }

    @Override
    public PageInfo<Shoe> pageList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);    //开启分页
        List<Shoe> list = shoeMapper.getAllShoes();   //service调用mapper
        return new PageInfo<>(list);
    }
} 